package com.spzx.test.t19;

import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class MyForkJoinCompute extends RecursiveTask<Long> {

    Long start = 0L;
    Long end = 0L;

    public MyForkJoinCompute(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        Long result = 0L;
        if(end-start<=10){
            // 能算开
            System.out.println(Thread.currentThread().getName()+"发现在自己的计算能力范围之内，开始运算");
            for (Long i = start; i <= end; i++) {
                result = result + i;
            }
        }else {
            // 算不开
            System.out.println(Thread.currentThread().getName()+"发现在自己的计算能力范围之外，算不开，开始拆分任务");
            Long lStart = start;
            Long lEnd = (start+end)/2;

            MyForkJoinCompute leftTask = new MyForkJoinCompute(lStart, lEnd);
            ForkJoinTask<Long> lFork = leftTask.fork();
            Long lJoin = lFork.join();

            Long rStart = lEnd +1;
            Long rEnd = end;
            MyForkJoinCompute rightTask = new MyForkJoinCompute(rStart, rEnd);
            ForkJoinTask<Long> rFork = rightTask.fork();
            Long rJoin = rFork.join();
            return lJoin + rJoin;
        }

        System.out.println(Thread.currentThread().getName()+"返回运算结果："+result);
        return result;
    }
}
